package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MyAdsDetail extends Activity {
	private final String LOAD_MY_AD = Singleton.getInstance().getHOST() + "shop-app/select-one-ad.php";
	private final String DELETE_MY_AD = Singleton.getInstance().getHOST() + "shop-app/update-ad-sold.php";
	private final String UPDATE_MY_AD = Singleton.getInstance().getHOST() + "shop-app/update-my-ad.php";
	private EditText descriptionInput;
	private EditText priceInput;
	private EditText titleInput;
	private Button updateAd;
	private Button deleteAd;
	private ImageView imageView;
	private Intent intent;
	
	private String currentId;
	private String currentTitle;
	private String currentPrice;
	private String currentImageURI;
	@SuppressWarnings("unused")
	private String currentCategory;
	private String currentDescription;
	private Bitmap currentImage;
	private final Misc misc = new Misc();
	
	private int updateState = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.my_ads_detail);
		iniGUIComponents();
		setEditableFields(false);
		
		updateAd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (updateState == 0) {
					updateState = 1;
					setEditableFields(true);
				} else {
					if (misc.validateInput(descriptionInput.getText().toString()) 
						&& misc.validateInput(priceInput.getText().toString())
						&& misc.validateInput(titleInput.getText().toString())) {
						new UpdateMyAd().execute();
					} else {
						if (!misc.validateInput(titleInput.getText().toString())) {
							misc.showErrorMessage("The title can NOT be empty!", getApplicationContext());
						} else if(!misc.validateInput(priceInput.getText().toString())){
							misc.showErrorMessage("The price can NOT be empty!", getApplicationContext());
						} else if(!misc.validateInput(descriptionInput.getText().toString())){
							misc.showErrorMessage("The description can NOT be empty!", getApplicationContext());
						} 
					}
					updateState = 0;
				}
			}
		});
		deleteAd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new DeleteAd().execute();
			}
		});
	}

	private void iniGUIComponents() {
		intent = getIntent();
		currentId = intent.getExtras().getString("id");
		descriptionInput = (EditText) findViewById(R.id.myAdDescription);
		priceInput = (EditText) findViewById(R.id.myAdPrice);
		titleInput = (EditText) findViewById(R.id.myAdTitle);
		updateAd = (Button) findViewById(R.id.btnUpdateAd);
		deleteAd = (Button) findViewById(R.id.btnDeleteAd);
		imageView = (ImageView) findViewById(R.id.myAdImage);
		new LoadAnAd().execute();
	}

	private void setEditableFields(Boolean isEditable){
		descriptionInput.setEnabled(isEditable);
		priceInput.setEnabled(isEditable);
		titleInput.setEnabled(isEditable);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.about_us, menu);
		return true;
	}

	private class LoadAnAd extends AsyncTask<String, String, String> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(MyAdsDetail.this);
	        pDialog.setMessage("Loading The Ad...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(true);
	        pDialog.show();
	    }
		@Override
		protected String doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("id", currentId));
            JSONObject json = jParser.makeHttpRequest(LOAD_MY_AD, values);
            try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                    currentTitle = json.getString("title");
                    currentPrice = json.getString("price");
                    currentImageURI = json.getString("image");
                    currentCategory = json.getString("category");
                    currentDescription = json.getString("description");
                    currentImage = misc.getImage(currentImageURI);
					
                } else {
                    Intent i = new Intent(getApplicationContext(), AdsActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
		@Override
		protected void onPostExecute(String op) {
			pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
				public void run() {
                	setTheView();
                }
            });
        }
	}
	@Override
	public void onBackPressed() {
		startActivity(new Intent(MyAdsDetail.this, MyAdsActivity.class));
		finish();
	}
	private class DeleteAd extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(MyAdsDetail.this);
	        pDialog.setMessage("Deleting The Ad...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(true);
	        pDialog.show();
	    }
		@Override
		protected Boolean doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("id", currentId));
            JSONObject json = jParser.makeHttpRequest(DELETE_MY_AD, values);
            try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                    return true;
                } else {
                    return false;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
 
		@Override
		protected void onPostExecute(Boolean op) {
			pDialog.dismiss();
            if (op) {
				 startActivity(new Intent(getApplicationContext(), MyAdsActivity.class));
				 finish();
			} else {
				misc.showErrorMessage("Couldn't delete the Ad", getApplicationContext());
			}
        }
	}
	
	private class UpdateMyAd extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(MyAdsDetail.this);
	        pDialog.setMessage("Updating Your Ad...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		@Override
		protected Boolean doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("id", currentId));
			values.add(new BasicNameValuePair("title", titleInput.getText().toString()));
			values.add(new BasicNameValuePair("price", priceInput.getText().toString()));
			values.add(new BasicNameValuePair("description", descriptionInput.getText().toString()));
            JSONObject json = jParser.makeHttpRequest(UPDATE_MY_AD, values);
            try {
				int success = json.getInt("affected");
				if (success == 1) {
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {}
			return null;
        }
 
		@Override
		protected void onPostExecute(final Boolean op) {
			pDialog.dismiss();
            if (op) {
            	runOnUiThread(new Runnable() {
					@Override
					public void run() {
						new LoadAnAd().execute();
		            	setEditableFields(false);
					}
				});
            	
			} else {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						misc.showErrorMessage("The Ad has not been updated!", getApplicationContext());
						new LoadAnAd().execute();
					}
				});
            	
				
			}
            
        }
	}
	
	private void setTheView() {
		titleInput.setText(currentTitle);
		priceInput.setText(currentPrice);
		descriptionInput.setText(currentDescription);
		imageView.setImageBitmap(currentImage);
	}
	
}
